import React, { useEffect, useState } from 'react';
import { Form, Input, Modal, Radio, Select, message } from 'antd';
import { ADDTK, getBuildingsList } from '../request';
const { TextArea } = Input;
const { Option } = Select;
import { useIntl } from '@umijs/max';
interface Props {
    isModalOpen: boolean;
    handleOk: () => void;
    handleCancel: () => void;
    setTKlist: any
    ModelMsg?: any
    flag: boolean
}
const App: React.FC<Props> = ({ isModalOpen, handleCancel, setTKlist, ModelMsg, flag }) => {
    const [form] = Form.useForm();
    const intl = useIntl();
    const [Bon, setBon] = useState<any>([])
    const getlist = async () => {
        const buildlist = await getBuildingsList()

        if (buildlist.data.list) {
            const newBon = buildlist.data.list.map((item: { bno: React.SetStateAction<undefined> }) => item.bno);
            setBon(newBon);
        }
    }
    useEffect(() => {
        if (flag == true) {
            form.setFieldsValue({
                bname: ModelMsg.bname,
                radioGroup: `${ModelMsg.permissions}`,
                remark: ModelMsg.remark
            });
        }
        getlist()
        getOption()
    }, [])


    const [optionArr, setoptionArr] = useState([])
    const getOption = () => {
        let arr = []
        for (let i = 0; i <= 100; i++) {
            arr.push(`${i+" "+ intl.formatMessage({id:"RoomSettings.Layer"})}`)
        }
        setoptionArr(arr)
    }
    function padSingleDigit(str: string | any[]) {
        
        if (str.length === 1) {
            return '0' + str;
        } else {
            return str;
        }
    }
    const handleOk = () => {
        form.validateFields().then(async (values) => {
            console.log(values)

            // 起始层
            setTKlist(values)
            let str = "" // roomid
            values.startFloor.map((item: string) => {
                let res2 = padSingleDigit(parseInt(values.bname).toString(16).toUpperCase())
                let res = padSingleDigit(parseInt(item).toString())

                str += res2 + parseInt(res).toString(16).toUpperCase().padStart(2, '0') + "0000"
                console.log("str", str)
            })
            // 公共层
            let str2 = ""
            if (values.publicFloor != undefined) {
                values.publicFloor.map((item: string) => {
                    let res = padSingleDigit(parseInt(item).toString())
                    str2 += parseInt(res).toString(16).toUpperCase().padStart(2, '0')
                })
            } else {
                str2 = "FFFFFFFF"
            }



            let str3 = 8 - str2.length
            if (str3 > 0) {
                for (var a = 0; a < str3; a++) {
                    str2 += "F"
                }
            }
            console.log(str)
            if (flag == true) {
                let data = await ADDTK({
                    id: ModelMsg.id,
                    bid: "01000000",
                    bname: values.bname,
                    startFloor: values.startFloor.join(","),
                    publicFloor: values.publicFloor ? values.publicFloor.join(",") : "",
                    pulicFloorId: str2,
                    remark: values.remark,
                    roomId: str,
                    permissions: values.radioGroup
                })
                if (data.code == "0") {
                    message.success(intl.formatMessage({id:"RoomSettings.Added successfully!"}))
                    handleCancel()
                } else {
                    message.error(data.msg)
                }
            } else {
                let data = await ADDTK({
                    bid: "01000000",
                    bname: values.bname,
                    startFloor: values.startFloor.join(","),
                    publicFloor: values.publicFloor ? values.publicFloor.join(",") : "",
                    pulicFloorId: str2,
                    remark: values.remark,
                    roomId: str,
                    permissions: values.radioGroup
                })
                if (data.code == "0") {
                    message.success(intl.formatMessage({id:"RoomSettings.Added successfully!"}))
                    handleCancel()
                } else {
                    message.error(data.msg)
                }
            }


        }).catch((errorInfo) => {
            console.log('Failed:', errorInfo);
        });
    };


    const onGenderChange = (value: string) => {
        console.log(value)
    };
    const [selectedOptions, setSelectedOptions] = useState([]);
    const [disableOptions, setDisableOptions] = useState(false);
    const [qishichenFlag, setqishichenFlag] = useState(false);
    const handleChange = (values) => {
        setSelectedOptions(values);

        if (values.length >= 4) {
            setDisableOptions(true);
        } else {
            setDisableOptions(false);
        }
    };
    const qishichen = (values: any) => {
        setSelectedOptions(values);

        if (values.length >= 1) {
            setqishichenFlag(true);
        } else {
            setqishichenFlag(false);
        }
    };
    return (
        <>
            <Modal title={intl.formatMessage({id:"RoomSettings.Add elevator control doors"})} open={isModalOpen}
                onOk={handleOk}
                onCancel={handleCancel}
                width={450}
            >

                <br />
                <Form
                    form={form}
                    name="basic"
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 16 }}
                    style={{ maxWidth: 600 }}
                    initialValues={{ remember: true }}
                    autoComplete="off"
                >
                    <Form.Item name="bname" label={intl.formatMessage({id:"FixLock.Building No"})} rules={[{ required: true, message:intl.formatMessage({id:'RoomSettings.Please select a building'}) }]}>
                        <Select
                            placeholder={intl.formatMessage({id:'RoomSettings.Please select a building'})}
                            onChange={onGenderChange}
                            allowClear
                        // mode="multiple"
                        >
                            {
                                Bon.map((item: string, index: number) => {
                                    return (
                                        <Option key={index} value={item}>{item}{intl.formatMessage({id:'FixLock.building'})}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item<any>
                        label={intl.formatMessage({ id: "FixLock.startFloor" })}
                        name="startFloor"
                        rules={[{ required: true, message: intl.formatMessage({ id: "FixLock.Please enter start floor" }) }]}
                    >
                        <Select
                            mode="multiple"
                            style={{ width: '100%' }}
                            placeholder={intl.formatMessage({ id: "FixLock.Please select a floor" })}
                            disabled={qishichenFlag}
                            onChange={qishichen}
                        >
                            {
                                optionArr.map((item, index) => {
                                    return (
                                        <Option key={index} value={item}>{item}</Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>

                    <Form.Item<any>
                        label={intl.formatMessage({ id: "FixLock.publicFloor" })}
                        name="publicFloor"
                    // rules={[{ required: true, message: '请输入公共层!' }]}

                    >
                        <Select
                            onChange={handleChange}
                            mode="multiple"
                            style={{ width: "100%" }}
                            placeholder={intl.formatMessage({ id: 'RoomSettings.public 4 floors.' })}
                            disabled={disableOptions}
                            value={selectedOptions}
                        >
                            {optionArr.map((item, index) => (
                                <Option key={index} value={item}>
                                    {item}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>

                    <Form.Item name="radioGroup" label={intl.formatMessage({ id: "FixLock.permissions" })} rules={[{ required: true, message: intl.formatMessage({ id: "RoomSettings.Please control permissions." }) }]}>
                        <Radio.Group>
                            <Radio value="1">{intl.formatMessage({id:"FixLock.Turn on the direct access feature"})}</Radio>
                            <Radio value="2">{intl.formatMessage({id:"FixLock.After swiping the card"})}</Radio>
                            <Radio value="3">{intl.formatMessage({id:"FixLock.Press all floors"})}</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item<any>
                        label={intl.formatMessage({ id: "FixLock.remark" })}
                        name="remark"
                    // rules={[{ required: true, message: '请输入梯控门备注!' }]}
                    >
                        <TextArea showCount maxLength={20} placeholder={intl.formatMessage({ id: "RoomSettings.Please remark" })} />
                    </Form.Item>
                </Form>

            </Modal>
        </>
    );
};

export default App;